/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.detail;

import static android.widget.Toast.LENGTH_SHORT;
import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_GET_COMMENT_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_GOODS_DETAIL_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.FAV_MARGIN;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_ID_KEY;

import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.activity.detail.adapter.ImageAdapter;
import com.dataoke.shoppingguide.app773026.activity.detail.adapter.ViewPagerAdapter;
import com.dataoke.shoppingguide.app773026.activity.detail.base.BaseDetailActivity;
import com.dataoke.shoppingguide.app773026.activity.detail.bean.DataokeGetCommentListResBean;
import com.dataoke.shoppingguide.app773026.activity.detail.fragment.CommentFragment;
import com.dataoke.shoppingguide.app773026.activity.detail.fragment.DetailFragment;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeGoodsDetailBean;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeGoodsDetailResBean;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeTaoWordBean;
import com.dataoke.shoppingguide.app773026.db.DaoUtilsStore;
import com.dataoke.shoppingguide.app773026.db.FavoriteBean;
import com.dataoke.shoppingguide.app773026.util.AppUtil;
import com.dataoke.shoppingguide.app773026.util.DaTaoKeUtil;
import com.dataoke.shoppingguide.app773026.util.HttpTools;
import com.dataoke.shoppingguide.app773026.util.ParseUtils;
import com.dataoke.shoppingguide.app773026.util.StatusBarUtils;
import com.dataoke.shoppingguide.app773026.util.ToastUtil;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class DataokeProductDetailActivity extends BaseDetailActivity {
    @BindView(R.id.shop_banner)
    Banner shopBanner;
    @BindView(R.id.shop_tablayout)
    TabLayout shopTablayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.shop_name_tv)
    TextView shopNameTv;
    @BindView(R.id.shop_end_price_tv)
    TextView shopEndPriceTv;
    @BindView(R.id.shop_price_tv)
    TextView shopVipPriceTv;
    @BindView(R.id.shop_specif_tv)
    TextView shopSpecifTv;
    @BindView(R.id.sales_volume_tv)
    TextView salesVolumeTv;
    @BindView(R.id.coupon_content_tv)
    TextView couponContentTv;
    @BindView(R.id.coupon_rl)
    LinearLayout couponRl;
    @BindView(R.id.share_tv)
    TextView serviceTv;
    @BindView(R.id.collection_tv)
    TextView collectionTv;
    @BindView(R.id.ll_take)
    LinearLayout llTake;
    @BindView(R.id.add_cart_btn)
    Button addCartBtn;
    @BindView(R.id.buy_now_btn)
    Button buyNowBtn;
    @BindView(R.id.coll_toolbar_layout)
    CollapsingToolbarLayout collToolbarLayout;
    @BindView(R.id.content_cl)
    FrameLayout contentCl;
    @BindView(R.id.ll_cart)
    LinearLayout llCart;
    @BindView(R.id.tv_take_name)
    TextView tvTakeName;
    private List<Fragment> list;
    private CommentFragment commentFragment = new CommentFragment();
    private DetailFragment detailFragment = new DetailFragment();
    private boolean isCollect = false;

    private DataokeTaoWordBean taoWordBean;
    private DataokeGoodsDetailBean itemBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_detail;
    }

    protected void initView() {
        viewPager.setOffscreenPageLimit(3);
        initBanner();
        initTabLayout();
        initData();
    }
    private void initData() {
    }
    private void buy() {
        if(taoWordBean!= null && taoWordBean.getCouponClickUrl() != null) {
            AppUtil.openApp(DataokeProductDetailActivity.this, taoWordBean.getCouponClickUrl());
        } else {
            DaTaoKeUtil.initTaoWord(itemBean.getGoodsId(), taoWordBean -> DataokeProductDetailActivity.this.taoWordBean = taoWordBean);
        }
    }
    String goodsId;
    private void initBanner() {
        goodsId = getIntent().getStringExtra(PRODUCT_ID_KEY);
        try {
            FavoriteBean favoriteBean = DaoUtilsStore.getInstance().getFavDaoUtils().queryByGoodsId(goodsId);
            if(favoriteBean != null) {
                setFavDrawable(R.mipmap.product_collection_selected);
            }
        }catch (Exception e) {
            Log.e("DataokeProductDetailActivity", e.getMessage());
        }

        shopBanner.isAutoLoop(false);
        HttpTools.get(String.format(DA_TAO_KE_GOODS_DETAIL_URL, goodsId), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("失败");
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    DataokeGoodsDetailResBean resBean = JSON.parseObject(response.body().string(), DataokeGoodsDetailResBean.class);
                    if(resBean.getCode() == 0) {
                        itemBean = resBean.getData();
                        runOnUiThread(() -> {
                            shopNameTv.setText(itemBean.getTitle());
                            shopEndPriceTv.setText(itemBean.getActualPrice() + "");
                            salesVolumeTv.setText("已售" + ParseUtils.getItemSale(itemBean.getMonthSales())+"件");
                            Spannable spanStrikethrough = new SpannableString(itemBean.getOriginalPrice() + "");
                            StrikethroughSpan stSpan = new StrikethroughSpan();  //设置删除线样式
                            spanStrikethrough.setSpan(stSpan, 0, spanStrikethrough.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            shopVipPriceTv.setText(spanStrikethrough);

                            String imagesStr = itemBean.getImgs();
                            List<String> images = Arrays.asList(imagesStr.split(","));

                            shopBanner.addBannerLifecycleObserver(DataokeProductDetailActivity.this)
                                    .setAdapter(new ImageAdapter(DataokeProductDetailActivity.this, images))
                                    .setIndicator(new CircleIndicator(DataokeProductDetailActivity.this));
                            String detailPics = itemBean.getDetailPics();
                            if(TextUtils.isEmpty(detailPics)) {
                                detailFragment.initData(images);
                            } else {
                                List<JSONObject> picList= JSON.parseArray(detailPics, JSONObject.class);
                                List<String> pics = picList.stream().map(pic-> {
                                    String imgUrl = pic.getString("img");
                                    return ParseUtils.getUrl(imgUrl);
                                }).collect(Collectors.toList());
                                detailFragment.initData(pics);
                            }
                            List<String> labels = JSON.parseArray(itemBean.getSpecialText(), String.class);
                            if(!labels.isEmpty()) {
                                for(String label: labels) {
                                    if(!label.contains("满")) {
                                        shopSpecifTv.setText(label);
                                    }
                                }
                            }
//                            Toast.makeText(DataokeProductDetailActivity.this, ScreenUtil.getScreenDp(DataokeProductDetailActivity.this) + "", Toast.LENGTH_LONG).show();
                            couponContentTv.setText(itemBean.getCouponPrice().intValue()+ "元优惠券");
                            if(!TextUtils.isEmpty(itemBean.getDesc())) {
                                llTake.setVisibility(View.VISIBLE);
                                tvTakeName.setText(itemBean.getDesc());
                            }
                            DaTaoKeUtil.initTaoWord(itemBean.getGoodsId(), taoWordBean -> DataokeProductDetailActivity.this.taoWordBean = taoWordBean);
                        });


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void initTabLayout() {
        list = new ArrayList<>();
        list.add(detailFragment);//宝贝详情
//        list.add(fmProductCase);//产品案例
//        list.add(commentFragment);//商品评价

        ViewPagerAdapter vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(vpAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener
                (shopTablayout));
        shopTablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener
                (viewPager));
        HttpTools.get(String.format(DA_TAO_KE_GET_COMMENT_LIST_URL, goodsId), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("失败");
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    DataokeGetCommentListResBean resBean = JSON.parseObject(response.body().string(), DataokeGetCommentListResBean.class);
                    if(resBean.getCode() == 0 && resBean.getData().getCommentList() != null) {
                        runOnUiThread(() -> {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("data", (ArrayList)resBean.getData().getCommentList());
                            commentFragment.setArguments(bundle);
                            list.add(commentFragment);
                            vpAdapter.notifyDataSetChanged();
                        });
                    } else {
                        runOnUiThread(() -> {
                            if(shopTablayout != null) {
                                shopTablayout.removeTabAt(1);
                            }
                        });
                    }
                }catch (Exception e) {
                }
            }
        });
    }


    @Override
    protected void addListener() {
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId()==android.R.id.home){
            finish();
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void setStatusBar() {
        StatusBarUtil.setTranslucentForImageView(DataokeProductDetailActivity.this, 0, null);
        StatusBarUtils.StatusBarLightMode(this, StatusBarUtils.StatusBarLightMode(this));
    }

    @OnClick({R.id.coupon_rl, R.id.share_tv, R.id.collection_tv, R.id.add_cart_btn, R.id.buy_now_btn, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_cart_btn://复制口令购买
                if(taoWordBean != null) {
                    setClipboard(taoWordBean.getTpwd(), "复制成功，打开【淘宝】领券购买");
                } else {
                    ToastUtil.show(getApplicationContext(), "复制成功，打开【淘宝】领券购买", LENGTH_SHORT);
                }
                break;
            case R.id.buy_now_btn://立即购买
            case R.id.coupon_rl:
                buy();
                break;
            case R.id.share_tv://分享
                if(itemBean != null && taoWordBean != null) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(itemBean.getTitle());
                    sb.append("\n原价：");
                    sb.append(taoWordBean.getOriginalPrice());
                    sb.append("  券后：");
                    sb.append(taoWordBean.getActualPrice());
                    sb.append("\n下单口令：");
                    sb.append(taoWordBean.getTpwd());
                    sb.append("\n下单链接：");
                    sb.append(taoWordBean.getKuaiZhanUrl());

                    setClipboard(sb.toString(), "复制成功，分享给好友");
                } else {
                    ToastUtil.show(getApplicationContext(), "复制成功，分享给好友", LENGTH_SHORT);
                }

                break;
            case R.id.collection_tv://收藏商品
                if(itemBean != null) {
                    if (isCollect) {
                        //请求取消收藏接口
                        FavoriteBean favoriteBean = new FavoriteBean();
                        favoriteBean.setGoodsId(itemBean.getGoodsId());
                        DaoUtilsStore.getInstance().getFavDaoUtils().delete(favoriteBean);
                        setFavDrawable(R.mipmap.product_collection_normal);
                    } else {
                        //获取收藏列表接口
                        FavoriteBean favoriteBean = new FavoriteBean();
                        favoriteBean.setGoodsId(itemBean.getGoodsId());
                        favoriteBean.setMainPic(itemBean.getMainPic());
                        favoriteBean.setTitle(itemBean.getTitle());
                        favoriteBean.setType(1);
                        boolean inserted = DaoUtilsStore.getInstance().getFavDaoUtils().insert(favoriteBean);
                        if(inserted){
                            setFavDrawable(R.mipmap.product_collection_selected);
                        }

                    }
                }
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
        }
    }

    protected void setFavDrawable(int resourceId) {
        Drawable drawable=getResources().getDrawable(resourceId);
        drawable.setBounds(0,0,FAV_MARGIN,FAV_MARGIN);
        collectionTv .setCompoundDrawables(null,drawable,null,null);
        if(resourceId == R.mipmap.product_collection_selected) {
            isCollect = true;
        }else{
            isCollect = false;
        }
    }
}